//
//  SendWarViewC.m
//  WHSport
//
//  Created by ccjoy-jimneylee on 15/4/14.
//  Copyright (c) 2015年 jimneylee. All rights reserved.
//

#import "SendWarViewC.h"
#import "VenuelistViewC.h"
#import "BusinessModel.h"
#import "UserModel.h"
#import "Util.h"

@interface SendWarViewC (){
    NSString *date;
    NSData *photoImg;
    NSString *type;
    NSString *typeID;
    NSString *level;
    NSArray *levelArray;
    NSString *placeName;
    NSString *placeID;
    NSArray *typeArray;
    NSString *typeNum;
}

@end

@implementation SendWarViewC
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title =@"发布约战";
    _placeImg.clipsToBounds = YES;
    _datePicker.hidden = YES;
    _pickerView.hidden = YES;
    
    levelArray =@[@"初级",@"中级",@"高级"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                        selector:@selector(Place:)
                                            name:@"NSNotification_PLACE"
                                               object:nil];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)Place:(NSNotification *)noti {
    NSDictionary *dic = [noti object];
    placeID = dic[@"id"];
    placeName = dic[@"name"];
    _placeLab.text = placeName;
}

#pragma mark - Table view data source
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == 0) {
        UIActionSheet *sheet;
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self
                                   cancelButtonTitle:nil destructiveButtonTitle:@"取消"
                                   otherButtonTitles:@"从相册选择",
                 nil];
        [sheet showInView:self.view];
    }
    
    if (indexPath.row == 1) {
        UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main"
                                                       bundle:nil];
        VenuelistViewC *venvc = [main instantiateViewControllerWithIdentifier:@"VenuelistViewC"];
        venvc.where = @"1";
        [self.navigationController pushViewController:venvc
                                             animated:YES];
    }
    
    if (indexPath.row == 2) {
        if (placeID.length == 0 || placeName.length == 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                                  @"提示" message:@"请先选择场馆"
                                  delegate:nil
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil];
            [alert show];
        }
        
        else{
            [[BusinessModel sharedInstance] getplaceDataHallWithsportsHallId:placeID getHallData:^(id info) {
                NSArray *array = [info copy];
                typeArray = array;
                typeNum = @"1";
                _pickerView.hidden = NO;
                [_pickerView reloadAllComponents];
            }];
        }
    }
    
    if (indexPath.row == 3) {
        _datePicker.hidden = NO;
        _datePicker.datePickerMode = UIDatePickerModeDate;
        [_datePicker addTarget:self action:@selector(timeChangede:) forControlEvents:UIControlEventValueChanged];
    }
    
    if (indexPath.row == 5) {
        typeNum =@"2";
        _pickerView.hidden = NO;
        [_pickerView reloadAllComponents];
    }
}

- (void)timeChangede:(UIDatePicker *)dagePicker {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    date = [dateFormatter stringFromDate:_datePicker.date];
    _timeLab.text = date;
    _datePicker.hidden = YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = 0;
    if (buttonIndex == 0) {
        return ;
    }
    //    if (buttonIndex == 1) {
    //        sourceType = UIImagePickerControllerSourceTypeCamera;
    //    }
    
    else{
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    
    UIImagePickerController *imageController = [[UIImagePickerController alloc] init];
    imageController.delegate = self;
    imageController.allowsEditing = YES;
    imageController.sourceType = sourceType;
    [self presentViewController:imageController animated:YES completion:^{
        
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image withName:@"currentImage.png"];
    
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
                      stringByAppendingPathComponent:@"currentImage.png"];
    UIImage *save = [[UIImage alloc] initWithContentsOfFile:path];

    _placeImg.image = save;
    photoImg = UIImageJPEGRepresentation(save, 0.5);
    
    }

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if ([typeNum isEqual:@"1"]) {
        return typeArray.count;
    }
    return levelArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([typeNum isEqual:@"1"]) {
        return [[typeArray objectAtIndex:row] objectForKey:@"event"];
    }
    else{
        return [levelArray objectAtIndex:row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{

    if ([typeNum isEqual:@"1"]) {
        type = [[typeArray objectAtIndex:row]
                         objectForKey:@"event"];
        typeID = [[typeArray objectAtIndex:row]
                objectForKey:@"id"];
        _typeLab.text = type;
        _pickerView.hidden = YES;
    }
    else{
        level = [levelArray objectAtIndex:row];
        _leveLab.text = level;
        _pickerView.hidden = YES;
    }
}

- (IBAction)sendBtn:(id)sender{
    
    NSString *count = _numField.text;
    
    if (date.length == 0 || type.length == 0 || placeName.length == 0 ||
        level.length == 0 || count.length == 0 || photoImg == nil) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:
                              @"提示" message:@"请将资料填写完整"
                                    delegate:nil
                                    cancelButtonTitle:@"确定"
                                    otherButtonTitles:nil, nil];
        [alert show];
        
        
    }
    
    else{
        NSString *mark = _makeField.text;
        if (mark.length == 0) {
            mark =@"";
        }
        NSString *fname = [NSString stringWithFormat:@"%d.png",
                           arc4random()];
        NSString *newL = [Util strWithlevel:level];
        NSString *meid = [UserModel sharedInstance].currentUser.ID;
        
        [[UserModel sharedInstance] sendWarWithaccountId:meid sportEventId:typeID sportsHallId:placeID timeLimit:date count:count level:newL remark:mark fileName:fname yuezhanpic:photoImg warData:^(BOOL successed, unsigned int value) {
            if (successed) {
                if (successed) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }
        }];
    
    }

}

@end
